AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )

include('shared.lua')

function ENT:Initialize()
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
	self.Entity:SetSolid( SOLID_VPHYSICS )

	local phys = self.Entity:GetPhysicsObject()
	
	if (phys:IsValid()) then
		phys:Wake()
	end
	
	self.SpawnTime = CurTime()

	self.Entity:SetColor( 0,0,0,255 )
    self.Entity:SetVar('lp',CurTime())

end

function SetupxcannonRound( round, cdata )
	round:SetVar('Cdata',cdata)
	round:PhysicsInitSphere( cdata.shellradius, "metal_bouncy" )
	round:SetNetworkedInt('ShellRadius',cdata.shellradius)
	round:SetNetworkedInt('TrailLength',cdata.traillength)
	round:SetVar('ShellGravity',cdata.shellgravity)
	local phys = round:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:Wake()
	end
	round:SetCollisionBounds( Vector( -cdata.shellradius, -cdata.shellradius, -cdata.shellradius ), Vector( cdata.shellradius, cdata.shellradius, cdata.shellradius ) )
end

function ENT:PhysicsCollide( data, physobj )
    local airtime = CurTime() - self.SpawnTime
	if airtime < 0.1 then return end -- dont asplode too soon.
	self:Explode()
end

function ENT:Explode()
	if ( !self.Entity:IsValid() ) then return end
	
	cdata = self.Entity:GetVar('Cdata',xcannon_types['xcannon'])
 	util.BlastDamage( self.Entity, self.Entity:GetVar('Owner',nil), self.Entity:GetPos(), cdata.radius, cdata.damage )

	local effectdata = EffectData()
		effectdata:SetOrigin( self.Entity:GetPos() )
	util.Effect( cdata.endeffect, effectdata, true, true )
	self.Exploding = true
end

function ENT:Think()
  local airtime = CurTime() - self.SpawnTime
  local sd = self.Entity:GetVar('selfdestruct',15.0)
  if ( airtime >= sd ) then
	self:Explode()
  end
  
  if self.Exploding then
   	self.Entity:Remove()
  end
end 

sv_gravity = server_settings.Int('sv_gravity',600)

function ENT:PhysicsUpdate( physobj )
	local dt = CurTime() - self.Entity:GetVar('lp',0)
	local gravpercent = self.Entity:GetVar('ShellGravity',1)
	local force = sv_gravity * physobj:GetMass() * dt * (1 - gravpercent)
	physobj:ApplyForceCenter(Vector(0,0,force))
	self.Entity:SetVar('lp',CurTime())
end
